(function(){
  const apiUrl = document.getElementById('apiUrl');
  const apiKey = document.getElementById('apiKey');
  const saveBtn = document.getElementById('saveBtn');
  const testBtn = document.getElementById('testBtn');
  const status = document.getElementById('status');

  function load(){
    chrome.storage.sync.get(["apiUrl", "apiKey"], (items)=>{
      apiUrl.value = items.apiUrl || '';
      apiKey.value = items.apiKey || '';
    });
  }

  function save(){
    const url = apiUrl.value.trim();
    const key = apiKey.value.trim();
    if(!url || !key){ status.textContent = '请填写完整信息'; return; }
    chrome.storage.sync.set({ apiUrl: url, apiKey: key }, ()=>{
      status.textContent = '已保存';
      setTimeout(()=> status.textContent = '', 2000);
    });
  }

  async function test(){
    const url = apiUrl.value.trim();
    const key = apiKey.value.trim();
    if(!url || !key){ status.textContent = '请先填写 API 与密钥'; return; }
    status.textContent = '测试中...';
    const fd = new FormData();
    fd.append('apikey', key);
    // 构造一个空文件 Blob 测试（部分服务端不接受空文件，这里仅探测认证错误码）
    fd.append('file', new Blob(["test"], {type: 'text/plain'}), 'test.txt');
    try{
      const res = await fetch(url, { method:'POST', headers:{'X-API-Key': key}, body: fd });
      const data = await res.json();
      status.textContent = '返回：' + (JSON.stringify(data));
    }catch(e){
      status.textContent = '网络错误：' + String(e);
    }
  }

  saveBtn.addEventListener('click', save);
  testBtn.addEventListener('click', test);
  load();
})();